package com.xm.xmapp.tools;

import java.math.BigDecimal;
import java.security.InvalidAlgorithmParameterException;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.widget.EditText;

import com.xm.xmapp.app.CodeConstant;

public class StringTools {

	/**
	 * ^1(3[0-9]|4[579]|5[0-35-9]|7[0135-8]|8[0-9])\\d{8}$
	 * 
	 * @param phone
	 * @return ^13[\d]{9}$|^14[\d]{9}$|^15[\d]{9}$|^17[\d]{9}$|^18[\d]{9}$
	 *         ^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$
	 */
	public static boolean isPhone(String phone) {
		if (phone == null)
			return false;
		Pattern p = Pattern.compile("^1[3-9]{1}\\d{9}$");
		// Pattern p = Pattern
		// .compile("^1(3[0-9]|4[579]|5[0-35-9]|7[0135-8]|8[0-9])\\d{8}$");
		Matcher m = p.matcher(phone);
		return m.matches();
	}

	/**
	 * 当浮点型数据位数超过10位之后，数据变成科学计数法显示。用此方法可以使其正常显示。
	 * 
	 * @param value
	 * @return Sting
	 */
	public static String formatFloatNumber(double value) {
		if (value != 0.00) {
			DecimalFormat df = new DecimalFormat("########0.00");
			return df.format(value);
		} else {
			return "0.00";
		}
	}

	/**
	 * 企业申请
	 * 
	 * @param str
	 * @return
	 * @throws PatternSyntaxException
	 */
	public static String stringFilter(String str) throws PatternSyntaxException {
		// 只允许字母、数字和汉字
		String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}

	/**
	 * 当浮点型数据位数超过10位之后，数据变成科学计数法显示。用此方法可以使其正常显示。
	 * 
	 * @param value
	 * @return Sting
	 */
	public static String formatFloatNumberMoney(double value) {
		int temp = (int) value;
		if (value != 0) {
			DecimalFormat df;
			if ((value / temp) != 1)
				df = new DecimalFormat("########0.00");
			else
				df = new DecimalFormat("########");
			return df.format(value);
		} else {
			return "0";
		}
	}

	public static boolean isBankNumber(String bankNumber) {
		if (bankNumber != null && !bankNumber.startsWith("0") && bankNumber.length() > 15 && bankNumber.length() < 20) {
			return true;
		}
		return false;
	}

	public static boolean isLength(String str, int minLength) {
		if (str == null || str.length() < minLength)
			return false;
		return true;

	}

	/**
	 * 验证输入ping码
	 * 
	 * @param edittext
	 * @return
	 */
	public static boolean isLength(EditText edittext) {
		String str = edittext.getText().toString();
		if (str.length() == 6 && isNumeric(str))
			return true;
		return false;
	}

	public static boolean checkQQ(String qq) {
		String regex = "[1-9][0-9]{4,14}";
		return qq.matches(regex);
	}

	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	public static String getString(float price) {
		DecimalFormat decimalFormat = new DecimalFormat("0.00");// 构造方法的字符格式这里如果小数不足2位,会以0补足.
		String p = decimalFormat.format(price);// format 返回的是字符串
		return p;
	}

	public static String getJuliString(float Juli, float s) {
		DecimalFormat decimalFormat;
		if (Juli < s)
			decimalFormat = new DecimalFormat("0");// 构造方法的字符格式这里如果小数不足2位,会以0补足.
		else {
			Juli /= 1000;
			decimalFormat = new DecimalFormat("0.00");
		}
		String p = decimalFormat.format(Juli);// format 返回的是字符串
		return p;
	}

	public static String getJuliString(float Juli) {
		DecimalFormat decimalFormat;
		if (Juli > 100)
			decimalFormat = new DecimalFormat("0");// 构造方法的字符格式这里如果小数不足2位,会以0补足.
		else
			decimalFormat = new DecimalFormat("0.00");
		String p = decimalFormat.format(Juli);// format 返回的是字符串
		return p;
	}

	public static String getString(Double price) {
		DecimalFormat decimalFormat = new DecimalFormat("0");// 构造方法的字符格式这里如果小数不足2位,会以0补足.
		String p = decimalFormat.format(price);// format 返回的是字符串
		return p;
	}

	public static String getString(Double price, String str) {
		DecimalFormat decimalFormat = new DecimalFormat(str);// 构造方法的字符格式这里如果小数不足2位,会以0补足.
		String p = decimalFormat.format(price);// format 返回的是字符串
		return p;
	}

	public static String getString(String str) {
		Double price = Double.parseDouble(str);
		DecimalFormat decimalFormat = new DecimalFormat("0.00");// 构造方法的字符格式这里如果小数不足2位,会以0补足.
		String p = decimalFormat.format(price);// format 返回的是字符串
		return p;
	}

	public static String getString1(String str) {
		Double price = Double.parseDouble(str);
		DecimalFormat decimalFormat = new DecimalFormat("0.00");// 构造方法的字符格式这里如果小数不足2位,会以0补足.
		String p = decimalFormat.format(price);// format 返回的是字符串
		return p;
	}

	public static String getLongTime(String time) {

		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 小写的mm表示的是分钟
			Date date = sdf.parse(time);
			sdf = new SimpleDateFormat("yyyy-MM-dd");
			String str = sdf.format(date);
			return str;
		} catch (Exception e) {
			return "";
		}
	}

	public static Date stringToDate(String strTime, String formatType) throws ParseException {
		SimpleDateFormat formatter = new SimpleDateFormat(formatType);
		Date date = null;
		date = formatter.parse(strTime);
		return date;
	}

	public static long stringToLong(String strTime, String formatType) throws ParseException {
		Date date = stringToDate(strTime, formatType); // String类型转成date类型
		if (date == null) {
			return 0;
		} else {
			long currentTime = dateToLong(date); // date类型转成long类型
			return currentTime;
		}
	}

	public static long dateToLong(Date date) {
		return date.getTime();
	}

	public static int getLongDay(String str1, String formatType1, String str2, String formatType2) {

		try {
			long time1 = stringToLong(str1, formatType1);
			long time2 = stringToLong(str2, formatType2);
			return (int) ((time2 - time1) / 1000 / 60 / 60 / 24);

		} catch (Exception e) {

		}
		return 0;
	}

	public static String getTime(long time, String str) {
		if (time == 0)
			return " ";
		SimpleDateFormat sdf = new SimpleDateFormat(str);
		String date = sdf.format(new Date(time));
		return date;
	}

	public static String getTime(long time) {
		String s = (time / 24 / 60 == 0 ? "" : (time / 24 / 60 + "天"))
				+ (time / 60 % 24 == 0 ? "" : (time / 60 % 24 + "小时")) + time % 60 + "分钟";
		return s;
	}

	/**
	 * 充电桩充电中调用
	 * 
	 * @param time
	 * @return
	 */
	public static String getTime1(long time)

	{
		String s = (time / 24 / 60 == 0 ? "" : (time / 24 / 60 + "d"))
				+ (time / 60 % 24 == 0 ? "" : (time / 60 % 24 + "h")) + time % 60 + "m";

		return s;

	}

	/**
	 * 
	 * @param filterString
	 *            过滤字符串
	 * @param length
	 *            字符串长度
	 * @return
	 */

	public static String tongXinFilterString(String filterString) {

		int length = filterString.length();
		if (filterString == null || filterString.trim().equals("")) {
			return "";
		}
		String filter = "";
		String str = filterString.replaceAll("//&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "");
		str = str.replaceAll("[(/>)<]", "");
		str = str.replaceAll("[a-zA-Z]", "");// 字母
		str = str.replaceAll("", "");// 数字

		// 会有 css样式过滤不了，判断从首个汉字开始截取—到最后
		char[] charValue = filter.toCharArray();
		for (int i = 0; i < charValue.length; i++) {
			if (isChinese(charValue[i])) {
				filter = filter.substring(i);
				break;
			}
		}

		int len = str.length();
		if (len <= length) {
			return str;
		} else {
			str = str.substring(0, length);
		}

		return str;
	}

	/**
	 * 判断是否是字符串
	 * 
	 * @param a
	 * @return
	 */
	public static boolean isChinese(char a) {
		return String.valueOf(a).matches("[\u4E00-\u9FA5]"); // 利用正则表达式，经测试可以区分开中文符号
	}

	public static String HtmlText(String inputString) {
		String htmlStr = inputString; // 含html标签的字符串
		String textStr = "";
		Pattern p_script;
		Matcher m_script;
		Pattern p_style;
		Matcher m_style;
		Pattern p_html;
		Matcher m_html;
		try {
			String regEx_script = "<[＼＼s]*?script[^>]*?>[＼＼s＼＼S]*?<[＼＼s]*?＼＼/[＼＼s]*?script[＼＼s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[＼＼s＼＼S]*?<＼＼/script>
																										// }
			String regEx_style = "<[＼＼s]*?style[^>]*?>[＼＼s＼＼S]*?<[＼＼s]*?＼＼/[＼＼s]*?style[＼＼s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[＼＼s＼＼S]*?<＼＼/style>
																									// }
			String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll(""); // 过滤script标签

			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll(""); // 过滤style标签

			p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll(""); // 过滤html标签

			/* 空格 —— */
			// p_html = Pattern.compile("＼＼ ", Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = htmlStr.replaceAll("&nbsp;", "");
			htmlStr = htmlStr.replaceAll(" ", "");
			textStr = htmlStr;

		} catch (Exception e) {
		}
		return textStr;
	}

	/**
	 * DES算法，加密
	 * 
	 * @param data
	 *            待加密字符串
	 * @param key
	 *            加密私钥，长度不能够小于8位
	 * @return 加密后的字节数组，一般结合Base64编码使用
	 * @throws InvalidAlgorithmParameterException
	 * @throws Exception
	 */
	public static String encode(String key, String data) {
		if (data == null)
			return null;
		try {
			DESKeySpec dks = new DESKeySpec(key.getBytes());
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			// key的长度不能够小于8位字节
			Key secretKey = keyFactory.generateSecret(dks);
			Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
			IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
			AlgorithmParameterSpec paramSpec = iv;
			cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
			byte[] bytes = cipher.doFinal(data.getBytes());
			return byte2hex(bytes);
		} catch (Exception e) {
			e.printStackTrace();
			return data;
		}
	}

	public static String getStringTime(int time) {
		String str = (time / 24 / 60 == 0 ? "" : (time / 24 / 60 + "天"))
				+ (time / 60 % 24 == 0 ? "" : (time / 60 % 24 + "小时")) + time % 60 + "分钟";
		return str;
	}

	public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding";

	/**
	 * 二行制转字符串
	 * 
	 * @param b
	 * @return
	 */
	private static String byte2hex(byte[] b) {
		StringBuilder hs = new StringBuilder();
		String stmp;
		for (int n = 0; b != null && n < b.length; n++) {
			stmp = Integer.toHexString(b[n] & 0XFF);
			if (stmp.length() == 1)
				hs.append('0');
			hs.append(stmp);
		}
		return hs.toString().toUpperCase();
	}

	/**
	 * 获取支付方式描述
	 * 
	 * @param payWay
	 * @return
	 */
	public static String getPayWay(int payWay) {
		// 支付方式：1=微信公众号支付，2=支付宝支付，3=银联支付,4=现金，5=钱包，6=微信app支付，7=活动,8=充值卡，9=银行转帐
		String myPayWay = null;
		switch (payWay) {
		case 1:
			myPayWay = "微信公众号支付";
			break;
		case 2:
			myPayWay = "支付宝支付";
			break;
		case 3:
			myPayWay = "网银支付";
			break;
		case 4:
			myPayWay = "现金";
			break;
		case 5:
			myPayWay = "钱包";
			break;
		case 6:
			myPayWay = "微信APP支付";
			break;
		case 7:
			myPayWay = "活动";
			break;
		case 8:
			myPayWay = "充值卡";
			break;
		case 9:
			myPayWay = "银行转帐";
			break;

		default:
			break;
		}
		return myPayWay;
	}

	/**
	 * 获取评价星星内容
	 * 
	 * @param count
	 * @return
	 */
	public static String getCommentText(int count) {
		String comment = "";
		switch (count) {
		case 1:
			comment = "非常差";
			break;
		case 2:
			comment = "比较差";
			break;
		case 3:
			comment = "一般";
			break;
		case 4:
			comment = "比较满意";
			break;
		case 5:
			comment = "非常满意";
			break;
		default:
			comment = "";
			break;
		}
		return comment;
	}

	public static SpannableStringBuilder getStyle(int start, String str, String str_text) {
		return getStyle(start, str, str_text, 0);
	}

	public static SpannableStringBuilder getStyle(int start, String str, String str_text, int textSize) {
		SpannableStringBuilder style = new SpannableStringBuilder(str_text);
		style.setSpan(new ForegroundColorSpan(Color.RED), start, start + str.length(),
				Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		if (textSize != 0)
			style.setSpan(new AbsoluteSizeSpan(textSize), start, start + str.length(),
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		return style;
	}

	/**
	 * 
	 * @param start从哪个位置开始
	 * @param str
	 *            变颜色的字
	 * @param str_text
	 *            总的文字
	 * @param textSize
	 *            变颜色文字的大小
	 * @param color
	 *            要变的颜色
	 * @return SpannableStringBuilder
	 */
	public static SpannableStringBuilder getStyle(int start, String str, String str_text, int textSize, int color) {
		SpannableStringBuilder style = null;
		try {
			style = new SpannableStringBuilder(str_text);
			style.setSpan(new ForegroundColorSpan(color), start, start + str.length(),
					Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
			if (textSize != 0)
				style.setSpan(new AbsoluteSizeSpan(textSize), start, start + str.length(),
						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return style;
	}

	// setSpan(new AbsoluteSizeSpan(20), 0, 6,
	// Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

	public static boolean isTime(String time_str) {
		// time_str = "10:00-15:00";
		if (time_str == null || time_str.equals(""))
			return false;
		String time[] = time_str.split("-");
		Date d = new Date();
		long nowTime = d.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String dateNowStr = sdf.format(d);
		time[0] = dateNowStr + " " + time[0];
		time[1] = dateNowStr + " " + time[1];
		try {
			long startTime = stringToLong(time[0], "yyyy-MM-dd HH:mm");
			long stopTime = stringToLong(time[1], "yyyy-MM-dd HH:mm");
			if (nowTime >= startTime && nowTime <= stopTime)
				return true;
		} catch (ParseException e) {
			e.printStackTrace();
			return false;
		}
		return false;
	}

	public static double getDdouble(double d) {
		BigDecimal b = new BigDecimal(d);
		double f = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
		return f;
	}

	/***
	 * 获取url 指定name的value;
	 * 
	 * @param url
	 * @param name
	 * @return
	 */
	private static String getValueByName(String url, String name) {
		String result = "";
		int index = url.indexOf("?");
		String temp = url.substring(index + 1);
		String[] keyValue = temp.split("&");
		for (String str : keyValue) {
			if (str.contains(name)) {
				result = str.replace(name + "=", "");
				break;
			}
		}
		return result;
	}

	/**
	 * 获取扫描后的二维码，取出其中的值
	 * 
	 * @param url
	 * @return
	 */

	public static JSONObject getObject(String url) {
		JSONObject htmlResponse = new JSONObject();
		try {
			if (url.startsWith(CodeConstant.HTML)) {
				htmlResponse.put("y", getValueByName(url, "y"));
				htmlResponse.put("t", getValueByName(url, "t"));
			} else {
				url = url.substring(CodeConstant.THTML.length());
				String[] mparms = url.split("\\.");
				htmlResponse.put("y", "000#" + mparms[0]);
				htmlResponse.put("t", 2);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return htmlResponse;
	}
}
